/**
*	Shenlene Cabigting
*/

import java.io.*;
import java.util.*;
import java.lang.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.text.SimpleDateFormat;

public class MyServlet extends HttpServlet implements Runnable {
	
	/**
	*
	*/
	
	private static Thread monitor;
	private static Balancer balancer;
	
	private static String destinationID;
	private static int state;
	
	public void init(ServletConfig config)
	throws ServletException {
		super.init(config);
		balancer = new Balancer();
		monitor = new Thread(this);
		monitor.start();
	}
	
	public void doGet(HttpServletRequest request, HttpServletResponse response) 
	throws ServletException, IOException {
		doPost(request, response);
	}
	public void doPost(HttpServletRequest request, HttpServletResponse response) 
	throws ServletException, IOException {
		if(isReady) {
			balancer.updateServerLoad(20, destinationID);
			response.sendRedirect("http://" + balancer.getServerPublicIP(destinationID));
		}
		else {
			response.setContentType("text/html");
			PrintWriter printWriter = response.getWriter();
			printWriter.println("<html>");
			printWriter.println("<head><title>Eucalyptus LSS Test Page</title></head>");
			printWriter.println("<body><div style = 'text-align: center;'><h2>Initializing servers. Please wait.</h2></div></body>");
			printWriter.println("</html>");
		}
	}
	
	/**
	*
	*/
	public void run() {
		while(true) {
			state = balancer.getState();
			
			if(state == constant.inactive) balancer.runInstance();
			else if(state == constant.active) destinationID = balancer.getDestination();
			
			try {
				monitor.sleep(5000);
			}
			catch (Exception e) {
				//
			}
		}
	}

}